package com.example.fw;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupData;
import com.example.utils.SortedListOf;

public class GroupHelper extends WebDriverHelperBase
{
	private SortedListOf<GroupData> cashedGroups;

	public GroupHelper(ApplicationManager manager)
	{
		super(manager);
	}

	public SortedListOf<GroupData> getUIGroups()
	{
		if (cashedGroups == null)
		{
			rebuildCash();
		}
		return cashedGroups;
	}

	public GroupHelper createGroup(GroupData group)
	{
		manager.navigateTo().groupsPage();
		initNewGroupCreation();
		fillGroupForm(group);
		submitGroupCreation();
		returnToGroupsPage();
		// rebuildCash();
		manager.getModel().addGroup(group);
		return this;
	}

	public GroupHelper modifyGoup(int index, GroupData group)
	{
		manager.navigateTo().groupsPage();
		initGroupModification(index);
		fillGroupForm(group);
		submitGroupModification();
		returnToGroupsPage();
		// rebuildCash();
		manager.getModel().removeGroup(index).addGroup(group);
		return this;
	}

	public GroupHelper deleteGroup(int groupNumber)
	{
		manager.navigateTo().groupsPage();
		selectGroupByIndex(groupNumber);
		submitGroupDeletion();
		returnToGroupsPage();
		// rebuildCash();
		manager.getModel().removeGroup(groupNumber);
		return this;
	}

	// ----------------------------------------------------->

	public void rebuildCash()
	{
		cashedGroups = new SortedListOf<GroupData>();

		manager.navigateTo().groupsPage();

		List<WebElement> checkboxes = driver.findElements(By.name("selected[]"));
		for (WebElement checkbox : checkboxes)
		{
			String title = checkbox.getAttribute("title");
			String name = title.substring("Select (".length(), title.length() - ")".length());
			cashedGroups.add(new GroupData().withName(name));
		}
	}

	public GroupHelper initNewGroupCreation()
	{
		click(By.name("new"));
		return this;
	}

	public GroupHelper fillGroupForm(GroupData group)
	{
		type(By.name("group_name"), group.getName());
		type(By.name("group_header"), group.getHeader());
		type(By.name("group_footer"), group.getFooter());
		return this;
	}

	public GroupHelper returnToGroupsPage()
	{
		click(By.linkText("group page"));
		return this;
	}

	private GroupHelper selectGroupByIndex(int groupNumber)
	{
		click(By.xpath(".//input[@name='selected[]'][" + (groupNumber + 1) + "]"));
		return this;
	}

	public GroupHelper initGroupModification(int groupNumber)
	{
		selectGroupByIndex(groupNumber);
		click(By.name("edit"));
		return this;
	}

	public GroupHelper submitGroupCreation()
	{
		click(By.name("submit"));
		// cashedGroups = null;
		return this;
	}

	public GroupHelper submitGroupModification()
	{
		click(By.name("update"));
		// cashedGroups = null;
		return this;
	}

	private GroupHelper submitGroupDeletion()
	{
		click(By.name("delete"));
		// cashedGroups = null;
		return this;
	}

}
